package utils

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

func GetCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0])) //返回绝对路径  filepath.Dir(os.Args[0])去除最后一个元素的路径
	if err != nil {
		fmt.Println("error ", err)
		return ""
	}
	//fmt.Println(dir)
	return dir
	//return strings.Replace(dir, "\\", "/", -1) //将\替换成/
}

func PathExists(path string) (os.FileInfo, error) {
	f, err := os.Stat(path)
	//fmt.Println(f.IsDir())
	if err == nil {
		return f, nil
	}
	if os.IsNotExist(err) {
		return nil, nil
	}
	return nil, err
}

func ListDir(dirPth string, suffix string) (files []string, err error) {
	if suffix != "" {
		return listDir_(dirPth, suffix)
	} else {
		return listDir(dirPth)
	}
}
func listDir_(dirPth string, suffix string) (files []string, err error) {
	files = make([]string, 0, 10)
	dir, err := ioutil.ReadDir(dirPth)
	if err != nil {
		return nil, err
	}
	PthSep := string(os.PathSeparator)
	suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写
	for _, fi := range dir {
		if fi.IsDir() { // 忽略目录
			continue
		}
		if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) { //匹配文件
			files = append(files, dirPth+PthSep+fi.Name())
		}
	}
	return files, nil
}
func listDir(dirPth string) (files []string, err error) {
	files = make([]string, 0, 10)
	dir, err := ioutil.ReadDir(dirPth)
	if err != nil {
		return nil, err
	}
	PthSep := string(os.PathSeparator)
	for _, fi := range dir {
		if fi.IsDir() { // 忽略目录
			continue
		}
		files = append(files, dirPth+PthSep+fi.Name())
	}
	return files, nil
}

//获取指定目录及所有子目录下的所有文件，可以匹配后缀过滤。
func WalkDir(dirPth, suffix string) (files []string, err error) {
	files = make([]string, 0, 30)
	suffix = strings.ToUpper(suffix)                                                     //忽略后缀匹配的大小写
	err = filepath.Walk(dirPth, func(filename string, fi os.FileInfo, err error) error { //遍历目录
		//if err != nil { //忽略错误
		// return err
		//}
		if fi.IsDir() { // 忽略目录
			return nil
		}
		if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) {
			files = append(files, filename)
		}
		return nil
	})
	return files, err
}

func WalkDirSize(path string, recursive bool) (totalbytes int64, filecount int64, err error) {
	var size int64
	var count int64
	var rerr error
	rerr = filepath.Walk(path, func(mpath string, info os.FileInfo, err2 error) error {
		depth := strings.Count(mpath, "\\") - strings.Count(path, "\\")
		//fmt.Println(depth)
		if depth > 0 && !recursive {
			return filepath.SkipDir
		} else {
			if !info.IsDir() {
				size += info.Size()
				count = count + 1
			}
		}
		return err2
	})
	return size, count, rerr
}
